package Demo;

public class MyQueue {
//    使用双向链表实现队列
//    先进先出
    static class ListNode{
        private int val;
        private ListNode prior;
        private ListNode next;

        public ListNode(int val){
            this.val = val;
        }
    }

    private ListNode front;// 队头
    private ListNode rear;// 队尾

    // 添加元素到队列的尾部
    public boolean offer(int x) {
        ListNode node = new ListNode(x);
        if (front == null){
            front = node;
            rear = node;
        } else {
            rear.next = node;
            node.prior = rear;
            rear = rear.next; // rear = node;
        }
        return true;
    }

    // 从队列的头部移除元素
    public Integer poll() {
        if (front == null) {
            return null;
        }

        int val = front.val;
        front = front.next;

        if (front == null) {
            rear = null;  // 如果移除后队列为空，将rear也置为null
        }

        return val;
    }

    public int peek(){
        return front.val;
    }

    public int size(){
        int count = 0;
        ListNode cur = front;

        while (cur != null) {
            count++;
            cur = cur.next;
        }

        return count;
    }

    public boolean isEmpty(){
        return front == null;
    }

}
